﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using Catering.View_Operaction;
using System.IO;

namespace Catering.Catering_Page.Kufang
{
    public partial class Kctz_info : System.Web.UI.Page
    {
        View_Operaction_Common voc = new View_Operaction_Common();
        DataBase_Manage_Operaction dmo = new DataBase_Manage_Operaction();
        public string strYear = string.Empty;


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string userid = Session["PersonnelID"].ToString();
                int companyid = 0;
                int groupid = 0;
                int classid = 0;
                bool isAdmin = false;
                Bind_Data_to_Controls.GetCompanyByCurrentUser(userid, out companyid, out groupid, out classid, out isAdmin);
                Bind_Data_to_Controls.Bind_Area_ddl(DDL_zuoyequ, isAdmin, groupid, companyid, false);
                Bind_Data_to_Controls.Bind_Class_ddl(DDL_zuoyequ.SelectedItem, DDL_banzu, isAdmin, classid, false);
                //int companyid = 0;
                //if (Session["UserID"] != null)
                //{
                //    string userid = Session["UserID"].ToString();
                //    companyid = new Catering_Rules.Personnel().GetCompanyIDByPID(Convert.ToInt32(userid));
                //}
                //voc.DropDownListDataBind_Group(this.DDL_zuoyequ, companyid);

                //if (DDL_zuoyequ.Items.Count > 0)
                //{
                //    voc.DropDownListDataBind_Class(this.DDL_banzu, DDL_zuoyequ.Items[0].Value);                //    

                //}
                voc.DropDownListDataBind_Database(this.DDL_kufang, DDL_zuoyequ.Items[0].Value, DDL_banzu.Items[0].Value);
                DataTable dt_kufang = new Catering_Rules.StorageRoom().GetAllList().Tables[0];
                this.DDL_kufang.LoadDrop(dt_kufang, "id", "RoomID", true);

            }
            ViewState["strYear"] = this.txt_nianfeng.Text.Trim();
            ViewState["Name"] = "";
        }

        //导出
        protected void BT_daochu_Click(object sender, EventArgs e)
        {

            Microsoft.Office.Interop.Excel.Application excel1 = null;
            Microsoft.Office.Interop.Excel.Workbooks books = null;
            Microsoft.Office.Interop.Excel.Workbook book = null;
            string stick = DateTime.Now.Ticks.ToString();

            try
            {

                excel1 = new Microsoft.Office.Interop.Excel.Application();
                excel1.Application.Workbooks.Add(true);//引用Excel工作簿
                excel1.Visible = false;
                books = (Microsoft.Office.Interop.Excel.Workbooks)excel1.Workbooks;
                book = books.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

                ViewState["Name"] = this.HidName.Value;
                int ClassID = Convert.ToInt32(this.DDL_banzu.SelectedValue);
                int RawID = Convert.ToInt32(this.HidID.Value);
                int YearID = Convert.ToInt32(this.txt_nianfeng.Text.Trim());
                string title = this.DDL_zuoyequ.SelectedItem.Text + this.DDL_banzu.SelectedItem.Text + this.DDL_kufang.SelectedItem.Text + "库房" + this.HidName.Value + "库存台账";

                for (int i = 1; i < 13; i++)
                {
                    DataTable dt = new Catering_DataSet.kucuntaizhangDataTable();
                    DateTime startTime = Convert.ToDateTime(YearID + "-" + i.ToString() + "-01");
                    for (DateTime time = startTime; time < startTime.AddMonths(1); time = time.AddDays(1))
                    {
                        DataTable dt_InOut = new Catering_Rules.InDbInfo().GetTZ(time.ToShortDateString(), ClassID, RawID).Tables[0];
                        if (dt_InOut.Rows[0]["InNumber"].ToString() != "" || dt_InOut.Rows[0]["OutNumber"].ToString() != "")
                        {
                            DataRow row = dt.NewRow();
                            row["riqi"] = time.ToShortDateString();
                            row["jiacharen"] = "";
                            row["jiecun"] = dt_InOut.Rows[0]["jieyu"].ToString();
                            row["danhao"] = "";
                            row["mingcheng"] = new Catering_Rules.T_RawMaterial().GetModel(RawID).RAWName;
                            row["ruku"] = dt_InOut.Rows[0]["InNumber"].ToString();
                            row["chuku"] = dt_InOut.Rows[0]["OutNumber"].ToString();
                            dt.Rows.Add(row);
                        }
                    }
                    GetKCTZ_Excel(book, dt, YearID + "年" + i + "月" + title);
                }
                if (!Directory.Exists(Server.MapPath("../../xls_template"))) Directory.CreateDirectory(Server.MapPath("../../xls_template"));
                book.SaveAs(Server.MapPath("../../xls_template") + "\\" + stick + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlAddIn8);
            }
            finally
            {
                if (excel1 != null)
                {
                    if (books != null)
                    {
                        if (book != null)
                        {
                            book.Close(false, null, null);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                            book = null;
                        }
                        books.Close();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
                        books = null;
                    }
                }
                excel1.Application.Workbooks.Close();
                excel1.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);
                Toolss.KillExcel(excel1);
                excel1 = null;
                GC.Collect();
            }

            #region 发送

            try
            {
                string path = Server.MapPath("../../xls_template") + "\\" + stick + ".xls";
                System.IO.FileInfo file = new System.IO.FileInfo(path);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息，,弹出另存为窗口  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                //让浏览器头显示下载信息  
                Response.AddHeader("Content-Length", file.Length.ToString());
                // 指定返回一个不能被客户端读取的流，下载  
                Response.ContentType = "application/ms-excel";
                //把文件流下载到客户端  
                Response.WriteFile(file.FullName);
                //Toolss.DeleteFile("../../xls_template/" + stick + ".xls");
                // 停止页面的执行
                Response.End();
            }
            catch { }

            #endregion
        }

        private void GetKCTZ_Excel(Microsoft.Office.Interop.Excel.Workbook book, DataTable dt, string title)
        {
            Microsoft.Office.Interop.Excel._Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题            

            #region 表头

            canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 8]); //取得合并的区域
            canbie.MergeCells = true;//合并单元格             
            ws.Cells[1, 1] = title;

            #endregion

            #region 标题行

            canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[2, 3]); //取得合并的区域
            canbie.MergeCells = true;//合并单元格 
            ws.Cells[2, 1] = "登记根据";
            ws.Cells[3, 1] = "月";
            ws.Cells[3, 2] = "日";
            ws.Cells[3, 3] = "单号";

            canbie = ws.get_Range(ws.Cells[2, 4], ws.Cells[3, 4]); //取得合并的区域
            canbie.MergeCells = true;//合并单元格 
            ws.Cells[2, 4] = "摘要";

            canbie = ws.get_Range(ws.Cells[2, 5], ws.Cells[2, 7]); //取得合并的区域
            canbie.MergeCells = true;//合并单元格 
            ws.Cells[2, 5] = "计划单价";
            ws.Cells[3, 5] = "收入数量";
            ws.Cells[3, 6] = "发出数量";
            ws.Cells[3, 7] = "结存数量";
            ws.Cells[2, 8] = "单位";
            ws.Cells[3, 8] = "检查人签章";

            #endregion

            #region 内容

            int starthang = 4;
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DateTime dtime = Convert.ToDateTime(dt.Rows[i]["riqi"]);
                    ws.Cells[starthang, 1] = dtime.Month;
                    ws.Cells[starthang, 2] = dtime.Day;
                    ws.Cells[starthang, 3] = dt.Rows[i]["danhao"];
                    ws.Cells[starthang, 4] = dt.Rows[i]["mingcheng"];
                    ws.Cells[starthang, 5] = dt.Rows[i]["ruku"];
                    ws.Cells[starthang, 6] = dt.Rows[i]["chuku"];
                    ws.Cells[starthang, 7] = dt.Rows[i]["jiecun"];
                    ws.Cells[starthang, 8] = dt.Rows[i]["jiacharen"];
                    starthang++;
                }
                dt.Dispose();
            }
            dt.Dispose();
            canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[(starthang - 1), 8]);
            canbie.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
            canbie.Borders.LineStyle = 1;
            ws.Cells.EntireColumn.AutoFit();//宽度自适应

            #endregion
        }

        //选择作业区
        protected void DDL_zuoyequ_SelectedIndexChanged(object sender, EventArgs e)
        {
            voc.DropDownListDataBind_Class(this.DDL_banzu, DDL_zuoyequ.SelectedValue);
        }

        //查询
        protected void BT_dayin_Click(object sender, EventArgs e)
        {
            if (this.HidID.Value == "-1")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择原料!');</script>");
                return;
            }

            if (this.txt_nianfeng.Text.Trim() == "")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择年份!');</script>");
                return;
            }

            ViewState["Name"] = this.HidName.Value;
            int ClassID = Convert.ToInt32(this.DDL_banzu.SelectedValue);
            int RawID = Convert.ToInt32(this.HidID.Value);
            int YearID = Convert.ToInt32(this.txt_nianfeng.Text.Trim());

            for (int i = 1; i < 13; i++)
            {
                DataTable dt = new Catering_DataSet.kucuntaizhangDataTable();
                DateTime startTime = Convert.ToDateTime(YearID + "-" + i.ToString() + "-01");
                for (DateTime time = startTime; time < startTime.AddMonths(1); time = time.AddDays(1))
                {
                    DataTable dt_InOut = new Catering_Rules.InDbInfo().GetTZ(time.ToShortDateString(), ClassID, RawID).Tables[0];
                    if (dt_InOut.Rows[0]["InNumber"].ToString() != "" || dt_InOut.Rows[0]["OutNumber"].ToString() != "")
                    {
                        DataRow row = dt.NewRow();
                        row["riqi"] = time.ToShortDateString();
                        row["jiacharen"] = "";
                        row["jiecun"] = dt_InOut.Rows[0]["jieyu"].ToString();
                        row["danhao"] = "";
                        row["mingcheng"] = new Catering_Rules.T_RawMaterial().GetModel(RawID).RAWName;
                        row["ruku"] = dt_InOut.Rows[0]["InNumber"].ToString();
                        row["chuku"] = dt_InOut.Rows[0]["OutNumber"].ToString();
                        dt.Rows.Add(row);
                    }

                }
                ViewState["showtaizhang_" + i] = dmo.ShowTaizhang(dt);
            }
        }
    }
}